package com.imooc.maokeyang.alllearning.service.impl;

import com.imooc.maokeyang.alllearning.exception.BusinessException;
import com.imooc.maokeyang.alllearning.exception.ErrorCodeEnum;
import com.imooc.maokeyang.alllearning.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;

/**
 * 本地上传服务
 */
@Service("localFileServiceImpl")
@Slf4j
public class LocalFileServiceImpl implements FileService {

    private static final String BUCKET = "uploads";

    @Override
    public void upload(InputStream inputStream, String fileName) {

        // 拼接文件的存储路径
        String storagePath = BUCKET + "/" + fileName;

        try (
            // JDK1.8 不能关闭外部资源(inputStream)
            InputStream innerInputStream = inputStream;
            FileOutputStream outputStream = new FileOutputStream(new File(storagePath));
        ) {
            // 拷贝缓冲区
            byte[] buffer = new byte[1024];

            // 读入文件流长度
            int len;

            // 循环读取流中的数据写入outputStream
            while ((len = innerInputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }
            // 冲刷流
            outputStream.flush();

        } catch (Exception e) {

            throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_FAILURE, e);
        }
    }

    @Override
    public void upload(File file) {
        try {
            upload(new FileInputStream(file), file.getName());
        } catch (FileNotFoundException e) {
            log.error("文件上传失败", e);

            throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_FAILURE, e);
        }
    }
}
